package com.example.aigc_education.integration.processor.v2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.integration.constants.CozeConstant;
import com.example.aigc_education.integration.request.CozeRequest;
import com.example.aigc_education.integration.response.CozeResponse;
import com.example.aigc_education.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * 同步工作流处理器
 * @param <T> 请求参数类型
 * @param <R> 响应结果类型
 */

@Slf4j
public abstract class CozeSyncProcessor<T, R> extends BaseCozeProcessor<T> {

    /**
     * 执行同步工作流
     *
     * @param request 请求参数
     * @return 处理结果
     */
    public R execute(CozeRequest<T> request, Class<R> responseType) {
        if (!isParamValid(request)) {
            log.warn("参数校验失败: {}", JsonUtils.toJson(request));
            throw new BusinessException("参数校验失败");
        }

        request.setWorkflowId(workflowId());
        request.setAsync(false);

        JSONObject jsonObject = (JSONObject) JSON.toJSON(request);
        String url = CozeConstant.COZE_URL + "/workflow/run";

        try {
            String restResult = executeHttpRequest(url, jsonObject);
            log.info("同步工作流执行结果: {}", restResult);

            CozeResponse cozeResponse = JsonUtils.fromJson(restResult, CozeResponse.class);
            String data = Optional.ofNullable(cozeResponse)
                    .map(CozeResponse::getData)
                    .orElse(null);

            log.info("同步工作流执行结果: {}", data);
            return Optional.ofNullable(data)
                    .map(d -> JsonUtils.fromJson(d, responseType))
                    .orElse(null);
        } catch (Exception e) {
            log.error("同步工作流执行异常", e);
            throw new BusinessException("执行工作流失败: " + e.getMessage());
        }
    }
}

